"""
@-*- coding: utf-8 -*-
@ python: 3.12.3
@ 创建者: JacksonCode
@ 创建时间: 2025-11-06
@ 描述: 用户相关业务逻辑
"""
from app.extensions import db
from app.models.users import User


class UserService:
    @staticmethod
    def get_all_users(page=1, per_page=10):
        """获取所有用户（分页）"""
        return User.query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
    
    @staticmethod
    def get_user_by_email(email):
        """根据邮箱获取用户"""
        return User.query.filter_by(email=email).first()
    
    @staticmethod
    def update_user_profile(user_id, data):
        """更新用户资料"""
        user = User.query.get(user_id)
        if not user:
            return None, "用户不存在"
        
        # 更新允许的字段
        if 'username' in data:
            user.username = data['username']
        
        if 'email' in data:
            # 检查邮箱是否已被其他用户使用
            existing_user = User.query.filter_by(email=data['email']).first()
            if existing_user and existing_user.id != user_id:
                return None, "邮箱已被其他用户使用"
            user.email = data['email']
        
        db.session.commit()
        return user, None
    
    @staticmethod
    def delete_user(user_id):
        """删除用户"""
        user = User.query.get(user_id)
        if user:
            db.session.delete(user)
            db.session.commit()
            return True
        return False
    
    @staticmethod
    def get_user_profile(user_id):
        """获取用户完整资料"""
        user = User.query.get(user_id)
        if user:
            return user.to_dict()
        return None